package com.lengxf.redis.service;


import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis服务操作类
 *
 * @Author Lengxf
 */
@Component
@AllArgsConstructor
@SuppressWarnings({"rawtypes", "unchecked"})
public class RedisService {

    private RedisTemplate redisTemplate;

    /**
     * 放入缓存
     *
     * @param key   键值
     * @param value 缓存数据
     * @Author Lengxf
     */
    public <T> void set(final String key, final T value) {
        redisTemplate.opsForValue().set(key, value);
    }


    public boolean expireKey(String key, long timeout) {
        return Boolean.TRUE.equals(redisTemplate.expire(key, timeout, TimeUnit.SECONDS));
    }

    /**
     * 过期缓存
     *
     * @param key     键值
     * @param value   缓存数据
     * @param timeout 超时时间
     * @Author Lengxf
     */
    public <T> void setWithExpire(final String key, final T value, final Long timeout) {
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断键值是否存在
     *
     * @param key 键值
     * @Author Lengxf
     */

    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 获取缓存对象
     *
     * @param key 键值
     * @Author Lengxf
     */
    public <T> T get(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }


    /**
     * 删除key
     *
     * @Author Lengxf
     */
    public Boolean remove(String key) {
        return redisTemplate.delete(key);
    }


}
